package com.server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.bean.Message;
import com.bean.ServletBean;
import com.server.servlet.Servlet;
import com.server.util.Config;
import com.server.util.XmlParseHelper;

public class SystemServerThread extends Thread {
	
	private ServerSocket mServer;
	private ExecutorService mExecutorService;
	
	public SystemServerThread() {
		try {
			int port = Integer.valueOf(Config.port);
			mServer = new ServerSocket(port);
			
			@SuppressWarnings("unused")
			int cpuCount = Runtime.getRuntime().availableProcessors();
			mExecutorService = Executors.newCachedThreadPool();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		while(true) {
			try {
				Socket socket = mServer.accept();
				mExecutorService.execute(new ServerRunnable(socket));
			} catch (IOException e) {
				e.printStackTrace();
			} 
		}
	}
	
	/**
	 * 收发数据线程
	 * @author zhangly
	 *
	 */
	private class ServerRunnable implements Runnable {
		
		private Socket mSocket;
		
		public ServerRunnable(Socket mSocket) {
			super();
			this.mSocket = mSocket;
		}

		@Override
		public void run() {
			ObjectInputStream inputStream = null;
			ObjectOutputStream outputStream = null;
			try {
				inputStream = new ObjectInputStream(mSocket.getInputStream());
				outputStream = new ObjectOutputStream(mSocket.getOutputStream());
				System.out.print(Thread.currentThread().getName() + "收到一条请求: ");
				
				Message message = (Message) inputStream.readObject();
				System.out.println(message);
				List<ServletBean> allBeans = XmlParseHelper.getAll("servlet.xml", ServletBean.class);
				for(ServletBean bean : allBeans) {
					if(message.getUrl().equals(bean.getUrl())) {
						Class<?> reqClass = Class.forName(bean.getClassName());
						Servlet servlet = (Servlet) reqClass.newInstance();
						servlet.receiveMessage(message);
						outputStream.writeObject(message);
						System.out.println(message);
						break;
					}
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} finally {
				try {
					if(inputStream != null) {
						inputStream.close();
					}
					if(outputStream != null) {
						outputStream.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
	};

}
